<template>
  <div>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchMethod">
          <a-row :gutter="24">


            <a-col :xl="3" :lg="7" :md="8" :sm="24">
              <a-form-model-item label="年级" prop="queryParam.gradeId">
                <!--              v-model="queryParam.gradeId"  对应java的Controller的接收参数vo对象的属性gradeId的值 -->
                <j-dict-select-tag @change="changeGradeId" v-model="queryParam.gradeId" placeholder="请选择年级"
                                   dictCode="cou_grade,grade_name,id,tenant_id  is not null order by  grade_order" />
              </a-form-model-item>
            </a-col>

            <a-col :xl="4" :lg="7" :md="8" :sm="24">
              <a-form-model-item label="考试" prop="queryParam.examinationId">
                <j-dict-select-tag v-model="queryParam.examinationId" placeholder="请选择考试"
                                   :dictCode="queryParamSelect.examinationIdSelect" />
              </a-form-model-item>
            </a-col>

            <a-col :xl="4" :lg="7" :md="8" :sm="24">
              <a-form-model-item label="计分范围(状态)" prop="queryParam.achievementStatus">
                <j-multi-select-tag
                  v-model="queryParam.achievementStatus"
                  dictCode="achievement_status"
                  placeholder="请选择">
                </j-multi-select-tag>
              </a-form-model-item>
            </a-col>
            <a-col :xl="3" :lg="7" :md="8" :sm="24">
              <a-form-model-item label="评分标准" prop="queryParam.achiStandPurposeType">
                <!--                <j-dict-select-tag @change='changeAchievementStandardId' v-model="queryParam.achievementStandardId"  :dictCode="queryParamSelect.achievementStandardIdSelect"/>-->
                <j-multi-select-tag
                  v-model="queryParam.achiStandPurposeType"
                  dictCode="achi_stand_purpose_type"
                  placeholder="请选择">
                </j-multi-select-tag>
              </a-form-model-item>
            </a-col>

            <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
<!--              <a-button type='primary' @click='loadDataTrRow2Col' icon='search'>查询</a-button>-->
              <a-button type="primary" icon="search" @click="goPreview">在线预览</a-button>
              <a-button type="primary" icon="download" @click="handleExportDocx('年级成绩分析报告1')">下载报告</a-button>
              <a-button type="primary" icon="upload" @click="searchMethod">保存服务器</a-button>
              <a-button type="primary" @click="resetSearchParams" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
            </a-col>
          </a-row>

          <template v-if="toggleSearchStatus">
            <a-row :gutter="24">
              <a-col :xl="4" :lg="7" :md="8" :sm="24">
                <a-form-model-item label="班级" prop="queryParam.classId">
                  <j-multi-select-tag v-model="queryParam.classId" placeholder="请选择班级"
                                     :dictCode="queryParamSelect.classIdSelect" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </template>
        </a-form>
      </div>

    </a-card>
    <div id="reportShow" style="text-align: center">
      <!--      <div v-html='sourceData' style='width: 595px;text-align: center' />-->
      <div class="docWrap">
        <!-- 预览文件的地方（用于渲染） -->
        <div ref="file"></div>
      </div>
    </div>
  </div>
</template>

<script>

import '@assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction ,downFile} from '@api/manage'
import { postAction } from '../../api/manage'
import { YEAR_SEMESTER } from '@/store/mutation-types'
import { filterObj } from '@/utils/util'
// import * as docx from "docx-preview";

let docx = require('docx-preview')
export default {
  name: 'analysisReport',
  mixins: [JeecgListMixin, mixinDevice],
  components: {},
  data() {
    return {
      sourceData: '',
      description: '成绩分析报告预览',
      url: {
        exportReport: '/analysisachievement/achstudent/report/index',
        showOnline: '/analysisachievement/achstudent/report/test',
        list: '/analysisachievement/achclasses/achClassAchievementExamScore/list',
        delete: '/analysisachievement/achclasses/achClassAchievementExamScore/delete',
        deleteBatch: '/analysisachievement/achclasses/achClassAchievementExamScore/deleteBatch',
        exportXlsUrl: '/analysisachievement/achclasses/achClassAchievementExamScore/exportXls',
        importExcelUrl: 'analysisachievement/achclasses/achClassAchievementExamScore/importExcel',
        poiExport: '/analysisachievement/achstudent/report/poi-report'
      },
      searchModal: {},
      dpSemester: 'cou_semester,semester_name,id',
      dpClass: 'cou_class,class_name,id',
      columns: [],
      queryParam: {
        achievementStatus: '1',    //考试状态(计分范围：1正常 2缺考 来自字典码 )
        achiStandPurposeType: '1',  //评分标准用途类型：1优良标准 2分档标准 （来自字典码）
        // subjectId: '-1',  //设置默认值：科目 -1代表总分
        //学期学年id
        schoolYearId: this.$ls.get(YEAR_SEMESTER).schoolYearId,
        semesterId: this.$ls.get(YEAR_SEMESTER).semesterId,
        schoolYearName: this.$ls.get(YEAR_SEMESTER).schoolYearName,
        semesterName: this.$ls.get(YEAR_SEMESTER).semesterName,
        gradeName: this.$ls.get(YEAR_SEMESTER).gradeName,
        downloadOrPreview: 'save' //下载或预览标识 downloadOrPreview "download"=下载  "preview"=预览 不允许为空
      },
      queryParamSelect: {
        examinationIdSelect: 'ach_examination,examination_name,id,del_flag  =0 and iz_open  =1  order by school_year_id desc !! semester_id !! grade_id !! create_time  desc',
        classIdSelect: 'cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 order by  class_order',
        examinationPaperIdSelect: 'ach_examination_paper aep,aep.examination_paper_name,aep.id,aep.iz_open =1 and aep.del_flag =0  order by examination_paper_name',
        achievementStandardIdSelect: null,
        // "ach_achievement_standard aas inner join rel_ach_standard_distribution rasd on aas.id = rasd.achievement_standard_id,aas.achievement_standard_name,aas.id,aas.iz_open =1 and aas.del_flag =0 and rasd.paper_standard_effective =1",
        achieveStandardItemIdSelect: null
        //"ach_achieve_standard_item,stand_item_name,id,iz_open =1 and del_flag =0 order by exa_pap_pro_item_code",
      }
    }
  },
  created() {
  },
  computed: {},
  methods: {
    handleExportDocx(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "年级成绩分析报告2"
      }
      this.queryParam.downloadOrPreview='download';
      let param = this.getQueryParams();
      if(this.selectedRowKeys && this.selectedRowKeys.length>0){
        param['selections'] = this.selectedRowKeys.join(",")
      }
      console.log("导出参数",param)
      downFile(this.url.poiExport,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}), fileName+'.docx')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.docx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    goPreview() {
      //下载或预览标识 downloadOrPreview "download"=下载  "preview"=预览 "save“=保存到服务器，不允许为空
      this.queryParam.downloadOrPreview='preview';
      let params = this.getQueryParams()
      getAction(this.url.poiExport, params).then(res => {
        // this.downloadWordFile(res, '成绩分析报告')
        docx.renderAsync(res.data, this.$refs.file) // 渲染到页面
      })
    },

      changeDPSemester() {
      if (this.searchModal.schoolYear != null) {
        this.dpSemester = 'cou_semester,semester_name,id where '
      }
    },
    changeClass() {
      if (this.searchModal.gradeName != null) {
        this.dpClass = 'cou_class,class_name,id,grade_code=' + this.searchModal.gradeName
      }
    },
    searchMethod() {
      //下载或预览标识 downloadOrPreview "download"=下载  "preview"=预览 "save“=保存到服务器，不允许为空
      this.queryParam.downloadOrPreview='save';
      let params = this.getQueryParams()
      getAction(this.url.poiExport, params).then(res => {
        if (res != null) {
          this.$message.success('成功获取预览')
          // this.sourceData = res
        } else {
          this.$message.error('预览生成失败')
        }
      })

    },
    resetSearchParams() {
      this.queryParam = {}
    },
    async loadDataTrRow2Col() {
      //获得测试数据
      // var testdata = this.dataSource ;
      var testdata = []
      this.defColumns = []
      this.columns = []
      this.settingColumns = []

      var params = this.getQueryParams()//查询条件
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          testdata = res.result.records
          // this.loadDataTrRow2ColUtil3(testdata);
          this.loadDataTrRow2ColInitColumns(testdata) //列名已经初始化了，只需初始化1次，不必重复初始化
          this.loadDataTrRow2ColInitDatas(testdata)  //更新数据样式格式

        }
      })
    },
    changeGradeId() {
      if (this.queryParam.gradeId) { //判断不为空
        this.queryParamSelect.examinationIdSelect = 'ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 and grade_id=\'' + this.queryParam.gradeId + '\' and school_year_id =\'' + this.queryParam.schoolYearId + '\' and semester_id =\'' + this.queryParam.semesterId + '\'   order by school_year_id desc !! semester_id !! grade_id !! create_time  desc'
        this.queryParamSelect.classIdSelect = 'cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 and grade_code=\'' + this.queryParam.gradeId + '\' order by  class_order'
      }
    },
    //更改考试-->选择试卷
    changeExaminationId() {
      if (this.queryParam.examinationId) {
        this.queryParamSelect.examinationPaperIdSelect = 'ach_examination_paper aep,aep.examination_paper_name,aep.id,aep.iz_open =1 and aep.del_flag =0 and aep.examination_id =\'' + this.queryParam.examinationId + '\'  order by aep.examination_paper_name'
        // this.queryParamSelect.achievementStandardIdSelect = "ach_achievement_standard,achievement_standard_name,id,iz_open =1 and del_flag =0  order by achievement_standard_order",
        // this.queryParamSelect.examinationIdSelect = "ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 and grade_id='"+ this.queryParam.gradeId +"' order by create_time  desc"
      }
    }
  }
}
</script>
<style scoped>
</style>